#include "registerdialog.h"
#include "ui_registerdialog.h"
#include "httpmgr.h"

#include <QtQml/QQmlContext>

RegisterDialog::RegisterDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::RegisterDialog)
{
    ui->setupUi(this);

    initHandlers();
    connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_reg_mod_finish, this, &RegisterDialog::slot_reg_mod_finish);
}

RegisterDialog::~RegisterDialog()
{
    qDebug("RegisterDialog::~RegisterDialog");
    delete ui;
}

void RegisterDialog::showTip(const QString &test, bool isOk)
{
    if(isOk){
        ui->Rtip->setProperty("state", "normal");
        repolish(ui->Rtip);
    }else{
        ui->Rtip->setProperty("state", "err");
        repolish(ui->Rtip);
    }
    ui->Rtip->setText(test);
}

void RegisterDialog::initHandlers()
{
    //获得验证码
    _handlers[ReqId::ID_GET_VARIFY_CODE] = [this](const QJsonObject& json){
        int err = json["error"].toInt();
        if (err != TipErr::TIP_SUCCESS){
            showTip("验证码获取失败", false);
            return;
        }
        showTip("验证码已发送，请注意查收", true);
    };

    //注册
    _handlers[ReqId::ID_REG_USER] = [this](const QJsonObject& json){
        int err = json["error"].toInt();
        if (err != TipErr::TIP_SUCCESS){
            showTip("注册失败", false);
            return;
        }
        showTip("您已成功注册，现在可以登录了", true);
    };
    _handlers[ReqId::ID_UPLOAD_AVATAR] = [this](const QJsonObject& json){

    };
}

void RegisterDialog::on_pushButton_2_clicked()
{
    if (ui->email_edit->text().isEmpty()){
        showTip("请输入邮箱", false);
        return;
    }

    static QRegularExpression regex("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
    QRegularExpressionMatch match = regex.match(ui->email_edit->text());
    if (!match.hasMatch()) {
        showTip("无效的邮箱地址", false);
        return;
    }

    QJsonObject userObject;
    userObject["email"] = ui->email_edit->text();
    HttpMgr::GetInstance()->PostHttpReq(QUrl(GATE_URL + "/user/verifyCode"),
                                        QJsonDocument(userObject).toJson(), ReqId::ID_GET_VARIFY_CODE, Modules::REGISTERMOD);
}

void RegisterDialog::on_pushButton_3_clicked()
{
    if(ui->user_edit->text() == ""){
        showTip(tr("用户名不能为空"), false);
        return;
    }
    if(ui->email_edit->text() == ""){
        showTip(tr("邮箱不能为空"), false);
        return;
    }
    if(ui->pass_edit->text() == ""){
        showTip(tr("密码不能为空"), false);
        return;
    }
    if(ui->confirm_edit->text() == ""){
        showTip(tr("确认密码不能为空"), false);
        return;
    }
    if(ui->confirm_edit->text() != ui->pass_edit->text()){
        showTip(tr("密码和确认密码不匹配"), false);
        return;
    }
    if(ui->varify_edit->text() == ""){
        showTip(tr("验证码不能为空"), false);
        return;
    }
    if(!ui->pushButton->text().isEmpty()){
        showTip(tr("请选择头像"), false);
        return;
    }

    QImage croppedPixmap(TemporaryAvatar);
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    buffer.open(QIODevice::WriteOnly);
    croppedPixmap.save(&buffer, "JPG");  // 可以选择其他格式如"JPG"

    QJsonObject json_obj;
    json_obj["username"] = ui->user_edit->text();
    json_obj["email"] = ui->email_edit->text();
    json_obj["password"] = ui->pass_edit->text();
    json_obj["confirm_password"] = ui->confirm_edit->text();
    json_obj["verification_code"] = ui->varify_edit->text();
    json_obj["avatar"] = QJsonValue::fromVariant(byteArray.toBase64());
    HttpMgr::GetInstance()->PostHttpReq(QUrl(GATE_URL+"/user/register"),
                                        QJsonDocument(json_obj).toJson(), ReqId::ID_REG_USER,Modules::REGISTERMOD);
}

void RegisterDialog::slot_reg_mod_finish(QByteArray data, ReqId id, ErrorCodes err)
{
    if (err != ErrorCodes::SUCCESS){
        showTip(data,false);
        return;
    }

    QJsonParseError jsonError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);

    if (jsonError.error != QJsonParseError::NoError){
        qDebug() << "JSON解析错误：" << jsonError.errorString();
        return;
    }

    _handlers[id](jsonDoc.object());
}


void RegisterDialog::on_pushButton_clicked()
{
    if (engine != nullptr){
        qDebug() << "engine";
        return;
    }

    engine = new QQmlApplicationEngine();
    //对qml暴露tailor
    tailor = new Tailor;
    connect(tailor, &Tailor::sig_head_portrait_finish, this,[this](){
        QPixmap ico(TemporaryAvatar);
        ui->pushButton->setIcon(ico);
        ui->pushButton->setIconSize(ui->pushButton->size());
        ui->pushButton->setText("");
    });
    connect(tailor, &Tailor::qmlClose, this, [this]{
        engine->deleteLater();
        tailor->deleteLater();
        tailor = nullptr;
        engine = nullptr;
    });
    engine->rootContext()->setContextProperty("tailor", tailor);
    engine->load(QUrl(QStringLiteral("qrc:/test/qrc/Main.qml")));
}
